package calao.util.xml;

import java.io.IOException;
import java.io.Writer;
import java.util.Stack;

public class XmlWriter {

	final Writer writer;
	final Stack<String> stack = new Stack<String>();

	public XmlWriter(Writer writer)
	{
		this.writer = writer;
	}

	public void startElement(String name, String... avPairs)
	throws IOException
	{
		startElement(name, avPairs, false);
	}
	
	public void flush()
	throws IOException
	{
		writer.flush();
	}

	void startElement(String name, String[] avPairs, boolean doStop)
	throws IOException
	{
		writer.write('<');
		writer.write(name);
		for (int i=0; i<avPairs.length; ) {
			String attrName = avPairs[i++];
			String attrValue = avPairs[i++];
			if (attrValue==null) continue;
			writer.write(' ');
			writer.write(attrName);
			writer.write("=\"");
			writer.write(attrValue);
			writer.write('"');
		}
		if (doStop) writer.write('/');
		else stack.push(name);
		writer.write('>');
	}

	public void writeElement(String name, String... avPairs)
	throws IOException
	{
		startElement(name, avPairs, true);
	}

	public void endElement()
	throws IOException
	{
		writer.write("</");
		writer.write(stack.pop());
		writer.write(">");
	}

	public void write(String text)
	throws IOException
	{
		for (int i=0; i<text.length(); i++) {
			char c = text.charAt(i);
			switch (c) {
			case '<':
				writer.write("&lt;");
				break;
			case '&':
				writer.write("&amp;");
				break;
			default:
				writer.write(c);
			}
		}
	}
	
	public void close()
	throws IOException
	{
		writer.close();
	}

}
